package com.taiji.dicom4cloud.smart.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taiji.dicom4cloud.common.core.utils.FileUtil;
import com.taiji.dicom4cloud.common.core.utils.R;
import com.taiji.dicom4cloud.common.model.entity.SysUser;
import com.taiji.dicom4cloud.common.security.utils.SecurityUtils;
import com.taiji.dicom4cloud.smart.model.entity.FtpFile;
import com.taiji.dicom4cloud.smart.service.FtpFileService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.Map;

@Api(description = "文件上传")
@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FtpFileService ftpFileService;

    @PostMapping("/photo-upload")
    @ResponseBody
    public R fileUpload(@RequestParam Map<String,String> map, MultipartFile file){

        String filePrefix = map.get("filePrefix");
        if(ObjectUtil.isNull(filePrefix)){
            SysUser sysUser = SecurityUtils.getUser();
            filePrefix = sysUser.getOrgId();
        }
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        fileName = new Date().getTime()+"."+suffix;
        String filepath = FileUtil.getStaticPath() +filePrefix+"/"+ fileName;
        File dest = new File(filepath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        if(dest.exists()){
            return R.ok(filepath);
        }
        try {
            file.transferTo(dest);
            return R.ok(filepath);
        } catch (Exception e) {
            log.error("上传文件失败！",e);
            return R.failed("null");
        }
    }

    @PostMapping("/ftp-file")
    public R pageFtpFile(Page page, FtpFile ftpFile){
        return R.ok(ftpFileService.getFtpFilePage(page,ftpFile));
    }
}
